package com.tiancheng.trade.payment.util.queue;

import com.tiancheng.trade.commom.core.utils.ServiceLocator;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: likailun
 * @Description: redis实现的延迟队列
 * @Date: create in 2022/4/7 3:57 下午
 */
@Slf4j
@Component
public class RedisDelayQueueUtil {
    @Autowired
    private RedissonClient redissonClient;

    private String getQueueKey(String queueCode) {
        final String env = ServiceLocator.getEnvironment();
        if (env.equals("dev") || env.equals("ldev")) {
            return queueCode + "_DEV";
        }
        return queueCode + "_PROD";
    }

    public <T> boolean addDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode) {
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(this.getQueueKey(queueCode));
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(value, delay, timeUnit);
            return true;
        } catch (RuntimeException e) {
            log.error("(添加延时队列失败) {}", e.getMessage());
            throw new RuntimeException("(添加延时队列失败)");
        }
    }

    /**
     * 获取延迟队列
     *
     * @param queueCode
     * @param <T>
     * @return
     * @throws InterruptedException
     */
    public <T> RBlockingQueue getDelayQueue(String queueCode) {
        RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(this.getQueueKey(queueCode));
        redissonClient.getDelayedQueue(blockingFairQueue);
        return blockingFairQueue;
    }
}
